<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{
            width: 800px;
            border: 1px solid #000;
            padding: 20px;
            background-color: #feeeed;
        }
    </style>
</head>
<body>
    <button onclick="loadHtml()">加载</button>


    <hr>


    <div id="box"></div>



    <script>
        // var a = '{"name":"什么","age":"12"}';
        // console.log(a);

        var a = 'var yy = { "name":"aiyoei","age":"18" }';
        eval(a);
        console.log(yy);

        // var yy = eval( '{"name":"lansou","age":"12"}' );
        // var yy = eval('({"name":"芸芸","age":"1888"})');
        // console.log(yy);
        // 
    
        //JSON 解析器
        // var yy = JSON.parse('("name":"里孩","age":"12")');
        // console.log(yy);

        function loadHtml() {
            var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4){
                        if(xhr.status == 200){
                            console.log(xhr.responseText);
                        //清空之前的数据
                        box.innerHTML = '';

                        var jsonStr = xhr.responseText;

                        var obj = JSON.parse(jsonStr);
                        console.log(obj);

                        //生成表格
                        var table = document.createElement('table');
                        table.width = 800;
                        table.border = 1;
                        table.cellSpacing = 0;
                        table.cellPadding = 5;
                        table.id = 'table';
                        console.log(table);
                        box.appendChild(table);


                        //添加表头
                        var tr = table.insertRow(0);
                        addTH(tr,['序号','名字','性别','年龄','省份']);

                        // 向表格添加数据
                        for (var i = 0; i < obj.length; i++) {
                            var tr = table.insertRow(i+1);
                            tr.insertCell(0).innerHTML = obj[i].id;
                            tr.insertCell(1).innerHTML = obj[i].name;
                            tr.insertCell(2).innerHTML = obj[i].sex;
                            tr.insertCell(3).innerHTML = obj[i].age;
                            tr.insertCell(4).innerHTML = obj[i].province;
                        }
                    }
                }
            }
            xhr.open('get','./php/4.php',true);
            xhr.send();
        }

        function addTH(tr,data){
            for (var i = 0; i < data.length; i++) {
                var th = document.createElement('th');
                th.innerHTML = data[i];
                tr.appendChild(th);
            }
        }


    </script>
</body>
</html>